package com.cooper.android.comm;

import com.cooper.scraper.R;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class AppDownReceiver extends DownReceiverChain {

	public AppDownReceiver() {
		super();
	}

	public AppDownReceiver(DownloadManager manager) {
		super(manager);
	}

	@Override
	protected boolean onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
			long downId = intent.getLongExtra(
					DownloadManager.EXTRA_DOWNLOAD_ID, -1);

			Cursor cursor = getDownloadManager(context).query(
					new DownloadManager.Query().setFilterById(downId));
			if (cursor != null) {
				try {
					if (cursor.moveToFirst()) {
						if (cursor
								.getString(
										cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION))
								.trim()
								.startsWith(
										context.getResources().getString(
												R.string.app_name)
												+ context
														.getResources()
														.getString(
																R.string.down_app_description))) {

							Intent installIntent = new Intent(
									Intent.ACTION_VIEW);

							installIntent
									.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							installIntent
									.setDataAndType(
											Uri.parse(cursor.getString(cursor
													.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))),
											"application/vnd.android.package-archive");
							context.startActivity(installIntent);
							return true;
						}
					}
				} finally {
					cursor.close();
				}
			}
		}
		return false;
	}

}
